<template>
  <div>
    <el-form inline>
      <el-form-item :label="queryTime.label">
        <el-date-picker :type="queryTime.type" v-model="queryParams.time" :value-format="queryTime.format"
          @change="handleDate" />
      </el-form-item>
      <el-form-item :label="$t('analysis.Dimension')">
        <el-radio-group v-model="groupBy" @change="doAnalysis">
          <el-radio-button label="deviceName">{{ $t('analysis.Locker') }}</el-radio-button>
          <el-radio-button label="storage">{{ $t('analysis.Storage') }}</el-radio-button>
          <el-radio-button v-if="queryTime.type === 'year'" label="month">{{ $t('analysis.Month') }}</el-radio-button>
          <el-radio-button v-if="queryTime.type === 'month'" label="date">{{$t('analysis.Day')}}</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('analysis.Index')">
        <el-radio-group v-model="valueType" @change="updateChart">
          <el-radio-button label="count">{{ $t('analysis.Count') }}</el-radio-button>
          <el-radio-button label="sum">{{ $t('analysis.Duration') }}</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>{{ $t('analysis.DayAndStorageTips',[totalDay,  totalChildrenCount]) }}</el-form-item>
      <!-- <el-form-item label="排序">
        <el-switch v-model="sourceAsc" active-text="由低到高" inactive-text="由高到低" @change="updateChart" />
      </el-form-item> -->
    </el-form>
    <div ref="chart" style="width: 90vw;height: 45vh;"></div>
    <!-- <div>{{ result }}</div> -->
  </div>
</template>
<script>
  import deviceAPI from '@/api/device/device'
  import deviceAnalysisAPI from '@/api/device/analysis'
  import * as echarts from 'echarts'
  import ListAnalysis from '@/utils/ListAnalysis'
  import {
    DeviceType
  } from '@/views/device/common'
  import {
    getLastMonthString,
    getMonthDayCount,
    subValueIn,
    parseDateLimit
  } from './utils'

  export default {
    name: 'UseBarByMonth',
    data() {
      return {
        chartOption: {
          title: {
            text: this.$t('analysis.UsingBarByMonth'),
            left: 'center'
          },
          tooltip: {
            show: true
          },
          xAxis: [{
            type: 'category'
          }],
          yAxis: [{
            type: 'value',
            show: true
          }],
          series: [{
            type: 'bar',
            name: this.$t('analysis.Duration')
          }]
        },
        queryTime: {
          label: this.$t('analysis.Month'),
          type: 'month',
          valueFormat: 'yyyy-MM'
        },
        queryParams: {
          time: null,
          startDate: null,
          endDate: null,
          deviceId: null
        },
        lockerList: [],
        permissions: [],
        chart: null,
        groupBy: 'deviceName',
        valueType: 'count',
        totalDay: 0,
        totalChildrenCount: 0,
        sourceAsc: false,
        result: {
          map: {},
          list: []
        },
      }
    },
    created() {
      this.setQueryTime()
      this.loadLocker()
      this.queryPermission()
    },
    mounted() {
      setTimeout(this.createChart, 300)
    },
    methods: {
      setQueryTime() {
        this.queryParams.time = getLastMonthString()
        this.totalDay = getMonthDayCount(this.queryParams.time)
      },
      handleDate() {
        this.totalDay = getMonthDayCount(this.queryParams.time)
        this.queryPermission()
      },
      loadLocker() {
        const vm = this
        deviceAPI.list({
          type: DeviceType.LOCKER
        }).then(res => {
          vm.lockerList = [].concat(res.data)
          const list = res.data
          var count = 0
          for (var i = 0; i < list.length; i++) {
            count += list[i].childrenSize
          }
          this.totalChildrenCount = count
        })
      },
      useMinute({
        startTime,
        endTime
      }, startMills, endMills) {
        return subValueIn(new Date(startTime).getTime(), (endTime === null ? new Date() : new Date(endTime)).getTime(),
            startMills, endMills) / 1000 /
          60
      },
      queryPermission() {
        const vm = this
        const {
          start,
          end
        } = parseDateLimit(this.queryParams.time)
        const startMills = start.getTime()
        const endMills = end.getTime()
        deviceAnalysisAPI.permissionList(this.queryParams).then(res => {
          vm.permissions = res.data.map(item => {
            item.minute = vm.useMinute(item, startMills, endMills)
            return item
          })
          vm.doAnalysis()
        })
      },
      createChart() {
        const el = this.$refs['chart']
        this.chart = echarts.init(el);
        this.chart.setOption(this.chartOption)
        this.updateChart();
      },
      doAnalysis() {
        const list = this.permissions
        if (list === null || list.length === 0) {
          this.result.list = []
        } else {
          const analysis = new ListAnalysis(list)
          var bys = this.groupBy === 'storage' ? ['deviceName', 'deviceIndex'] : [this.groupBy]
          this.result = analysis.groupBy(bys, ['minute'])
        }
        this.updateChart()
      },
      updateChart() {
        if (this.chart === null) {
          return
        }
        const {
          list,
          map
        } = this.result
        const source = this.groupBy === 'storage' ? list.map(item => {
          item.storage = item.deviceName + '_' + item.deviceIndex
          return item
        }) : list
        const valueColumns = ['minute-count', 'minute-sum']
        const dimensions = [this.groupBy].concat(this.valueType === 'count' ? valueColumns : valueColumns.reverse())
        const updateOption = {
          yAxis: [{
            name: this.valueType === 'count' ? this.$t('analysis.Count') : this.$t('analysis.Minute')
          }],
          dataset: [{
            dimensions,
            source
          }],
          series: [{
            type: 'bar',
            name: this.valueType === 'minute' ? this.$t('analysis.StoreDuration') : this.$t('analysis.StoreCount')
          }]
        }

        const categorys = []
        if (this.groupBy === 'deviceName') {
          for (var i = 0; i < this.lockerList.length; i++) {
            const item = this.lockerList[i]
            categorys.push(item.name)
          }
        } else if (this.groupBy === 'storage') {
          for (var i = 0; i < list.length; i++) {
            const item = list[i]
            categorys.push(item.storage)
          }
        } else if (this.groupBy === 'month') {
          for (var i = 0; i < list.length; i++) {
            const item = list[i]
            categorys.push(item.month)
          }
        } else if (this.groupBy === 'date') {
          for (var i = 1; i <= this.totalDay; i++) {
            categorys.push(this.queryParams.time + '-' + i)
          }
        }

        updateOption.xAxis = [{
          data: categorys
        }]
        this.chart.setOption(updateOption);
      }
    }
  }

</script>
